/**
 * 设置axios的拦截器及公共的参数
 */
import Vue from 'vue';
import axios from 'axios';
import store from '../../vuex/store';
import router from '../../config/routes';
import Util from "@/common/util.js";
import Wcontext from './context.js';
import {Loading, Message} from 'element-ui'

// axios 配置
// axios.defaults.timeout = 5000
axios.defaults.baseURL = ''
//用来处理刷新token后重新请求的自定义变量
axios.defaults.isRetryRequest = false

// 是否正在刷新的标志 
window.isRefreshing = false; 

let refreshSubscribers = [];


function getRefreshToken() {
    //refresh_token使用vuex存在本地的localstorage，之后会详细说
    let params = {
    	grantType: 'refresh_token',
    	refreshToken: store.getters.auth_refresh_token_id
    };
    return axios.post('/woauth/token', params);
}

/**
 * 登出系统
 */
function logoug() {
	store.dispatch('authLogout');
	window.location.href = Util.loginPath();
}


// http request 拦截器
var loadinginstace;
axios.interceptors.request.use(
    config => {
		
		if(config.url != '/woauth/token') {
			//获取储存在本地的token值
			let authToken = store.getters.auth_token_id;
			config.headers.Authorization = `Bearer ` + authToken
		}

        //这是element-ui的效果，全页面遮罩，中间带有加载圈
        loadinginstace = Loading.service({fullscreen: true})
        return config
    },
    err => {
        //这边是参考上面的链接的，具体有什么用我目前还没测到，反正加载超时不是在这边显示
        loadinginstace.close()
        Message.error({
            message: '加载超时'
        })
        return Promise.reject(err)
    }
);

// http response 拦截器
axios.interceptors.response.use(
    response => {
        //关闭遮罩层，非常重要，不然页面都不能操作了！
        loadinginstace.close();
        return response
    },
    err => {
        if (err.response) {
            switch (err.response.status) {
                case 401:
                    let config = err.config;
										if(config.url != '/ws/logout') {
											logoug();
											break;
										}
                    
										refreshSubscribers.push(config);
										if(!window.isRefreshing) {
											window.isRefreshing = true;
											return getRefreshToken()
												.then(function (res) {
													let data = res.data;
													if(data.meta.code == 0) {
														let tokenData = data.data;
														localStorage.setItem(Util.tokenKey(), JSON.stringify(tokenData));
														store.dispatch('authFlushToken');
														// config.isRetryRequest = true;
														window.isRefreshing = false;
														
														//修改原请求的token
														let authToken = store.getters.auth_token_id;
														config.headers.Authorization = `Bearer ` + authToken;
														
														return new Promise((resolve, reject) => {
															for(let i = 0; i < refreshSubscribers.length; i++) {
																axios(refreshSubscribers[i]);
															}
															refreshSubscribers = [];
															resolve();
														});
													} else {
														store.dispatch('authLogout');
														window.location.href = Util.loginPath();
													}
													
												})
												.catch(function () {
													//刷新token失败只能跳转到登录页重新登录
													store.dispatch('authLogout');
													window.location.href = Util.loginPath();
													throw err;
												});
											
										}
                    
                    break;
            }
        }
        else{
            Message.error({
                message: '加载超时'
            })
        }
        loadinginstace.close();
        return Promise.reject(err)
    }
);

export default axios;